package top.wilsonlv.jaguar.cloud.auth.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.wilsonlv.jaguar.cloud.auth.oauth2.AuthServerTokenServices;
import top.wilsonlv.jaguar.commons.web.exception.impl.CheckedException;
import top.wilsonlv.jaguar.commons.web.response.JsonResult;

import javax.validation.constraints.NotBlank;

/**
 * @author lvws
 * @since 2021/12/17
 */
@RestController
@RequestMapping("/oauth/token")
@RequiredArgsConstructor
@Api(tags = "oauth token api")
public class TokenApi {

    private final AuthServerTokenServices authServerTokenServices;

    private final int TOKEN_MIN_LENGTH = OAuth2AccessToken.BEARER_TYPE.length() + 1;

    @ApiOperation(value = "注销认证令牌")
    @DeleteMapping("/logout")
    public JsonResult<Void> logout(@RequestHeader(HttpHeaders.AUTHORIZATION)
                                   @NotBlank(message = "Authorization为非空") String token) {
        if (token.length() <= TOKEN_MIN_LENGTH) {
            throw new CheckedException("无效的Authorization");
        }

        authServerTokenServices.revokeToken(token.substring(TOKEN_MIN_LENGTH));
        return JsonResult.success();
    }

}
